var thematicGraphicLayer;
var initAddressSearch;
var addressSearchText;

require([
    "dojo/on",
    "esri/symbols/PictureMarkerSymbol", "esri/layers/GraphicsLayer",
    "esri/graphic", "esri/InfoTemplate",
    "esri/geometry/Point", "esri/geometry/Circle",
    "dojo/domReady!"
], function (
    on, PictureMarkerSymbol, GraphicsLayer, Graphic,
    InfoTemplate, Point, Circle) {

    initAddressSearch = function () {
        thematicGraphicLayer = new GraphicsLayer({
            id: "thematicGraphicLayer"
        });
        map.addLayer(thematicGraphicLayer);
    }
    //地址检索
    $("#menpaiInput").on("keypress", function (event) {
        if (event.keyCode == 13) {
            $("#menpaiSearBtn").click();
        }
    })

    var addressResult = [];
    $("#menpaiSearBtn").click(function () {
        menpai = true;
        addressSearchText = $("#menpaiInput").val();
        if (addressSearchText.trim().length === 0) {
            $("#menpaiInput").focus();
            return;
        }
        $("#addressList>ul").empty();
        $("#addressList .waitPanel").show();
        $.ajax({
            url: oneMapServerIP+"/OneMapServer/rest/services/address_p/as_CH.asmx/ASCH_AddressSearch?vSearch_word=" + addressSearchText + "&vResult_count=1000&token=" + GLOBAL_TOKEN,
            type: "get",
            dataType: "XML",
            success: function (response) {
                map.infoWindow.hide();
                $("#addressList .waitPanel").hide();

                if (response.getElementsByTagName("DZ_Result")[0].getElementsByTagName("Result_Flag").length == 0) {
                    $("#addressList>ul").text("在上海市范围内未找到相关地点。");
                    return;
                }
                addressResult = response.getElementsByTagName("DZ_Result")[0].getElementsByTagName("DZ_Table")[0].children[1].children[0].children;

                if (addressResult.length > 0) {
                    $("#addressPage").initPage(addressResult.length, 1, buildAddress);
                }
            }
        });
    });

    function buildAddress(page) {
        $("#addressList>ul").empty();
        var sli = "<li><span class='data_count'>共有" + addressResult.length + "个结果</span><button class='btn btn-success exportBtn' id='exportCSV2'>导出</button></li>"
        $("#addressList>ul").append(sli);
        aroundGraphicLayer.clear();
        thematicGraphicLayer.clear();

        var max = page * 10;

        if (max > addressResult.length) {
            max = addressResult.length
        }

        var addressGraphicArr = [];

        for (var i = 0; i < addressResult.length; i++) {
            var item = addressResult[i];
            var attr = {};

            //统一名称
            var addname = "";

            if (null != item.getElementsByTagName("POI")[0] && item.getElementsByTagName("POI")[0].textContent != null) {
                addname = item.getElementsByTagName("POI")[0].textContent;
            } else if (null != item.getElementsByTagName("ROAD1")[0] && item.getElementsByTagName("ROAD1")[0].textContent != null) {
                addname = item.getElementsByTagName("ROAD1")[0].textContent;
            } else if (null != item.getElementsByTagName("ADDRESS")[0] && item.getElementsByTagName("ADDRESS")[0].textContent != null) {
                addname = item.getElementsByTagName("ADDRESS")[0].textContent;
            }

            var area = "";

            if (null != item.getElementsByTagName("REGION_QX")[0] && item.getElementsByTagName("REGION_QX")[0].textContent != null) {
                area = item.getElementsByTagName("REGION_QX")[0].textContent;
            } else {
                area = "上海市";
            }

            var maccuracy = "";
            if (null != item.getElementsByTagName("MACCURACY")[0] && item.getElementsByTagName("MACCURACY")[0].textContent != null) {
                maccuracy = item.getElementsByTagName("MACCURACY")[0].textContent;
            } else {
                maccuracy = "0";
            }

            if (null != item.getElementsByTagName("POINT_X")[0] && item.getElementsByTagName("POINT_X")[0].textContent != null && null != item.getElementsByTagName("POINT_Y")[0] && item.getElementsByTagName("POINT_Y")[0].textContent != null) {
                var x = parseFloat(item.getElementsByTagName("POINT_X")[0].textContent);
                var y = parseFloat(item.getElementsByTagName("POINT_Y")[0].textContent);
            } else {
                return
            }

            attr["name"] = addname;
            attr["district"] = area;
            attr["x"] = x;
            attr["y"] = y;
            attr["maccuracy"] = maccuracy;

            var pt = new Point(x, y, map.spatialReference);

            var graphic = new Graphic(pt, null, attr, null);
            addressGraphicArr.push(graphic);
        }


        for (var i = (page - 1) * 10; i < max; i++) {
            var item = addressResult[i];
            var attr = {};

            var infoCont = "";
            //统一名称
            var addname = "";

            if (null != item.getElementsByTagName("POI")[0] && item.getElementsByTagName("POI")[0].textContent != null) {
                addname = item.getElementsByTagName("POI")[0].textContent;
            } else if (null != item.getElementsByTagName("ROAD1")[0] && item.getElementsByTagName("ROAD1")[0].textContent != null) {
                addname = item.getElementsByTagName("ROAD1")[0].textContent;
            } else if (null != item.getElementsByTagName("ADDRESS")[0] && item.getElementsByTagName("ADDRESS")[0].textContent != null) {
                addname = item.getElementsByTagName("ADDRESS")[0].textContent;
            }

            if (null != item.getElementsByTagName("POINT_X")[0] && item.getElementsByTagName("POINT_X")[0].textContent != null && null != item.getElementsByTagName("POINT_Y")[0] && item.getElementsByTagName("POINT_Y")[0].textContent != null) {
                var x = parseFloat(item.getElementsByTagName("POINT_X")[0].textContent);
                var y = parseFloat(item.getElementsByTagName("POINT_Y")[0].textContent);
            } else {
                return
            }

            var area = "";

            if (null != item.getElementsByTagName("REGION_QX")[0] && item.getElementsByTagName("REGION_QX")[0].textContent != null) {
                area = item.getElementsByTagName("REGION_QX")[0].textContent;
            } else {
                area = "上海市";
            }

            var maccuracy = "";
            if (null != item.getElementsByTagName("MACCURACY")[0] && item.getElementsByTagName("MACCURACY")[0].textContent != null) {
                maccuracy = item.getElementsByTagName("MACCURACY")[0].textContent;
            } else {
                maccuracy = "0";
            }

            attr["name"] = addname;
            attr["district"] = area;
            attr["x"] = x;
            attr["y"] = y;
            attr["maccuracy"] = maccuracy;

            var sms = new PictureMarkerSymbol("img/marker/" + (i + 1 - (page - 1) * 10) + ".png", 30, 30);
            var pt = new Point(x, y, map.spatialReference);

            infoCont += "<b>区县" + ":</b> " + area + " <br/>";

            var infoTemplate = new InfoTemplate("<b>" + addname + "</b>", infoCont);
            var graphic = new Graphic(pt, sms, attr, infoTemplate);
            // addressGraphicArr.push(graphic);

            thematicGraphicLayer.add(graphic);

            var li = document.createElement("li");
            var corp_name = document.createElement("p");
            corp_name.className = "corp_name";
            // corp_name.innerHTML = "<i class=\"fa fa-map-marker\"></i>" + "&nbsp" + addname;
            corp_name.innerHTML = "<img height='25px' src='img/marker/" + (i + 1 - (page - 1) * 10) + ".png'/>" + "&nbsp" + addname;

            var person_name = document.createElement("p");
            person_name.className = "person_name";
            person_name.innerHTML = area;

            li.appendChild(corp_name);
            li.appendChild(person_name);

            $("#addressList>ul").append(li);

            if (i - (page - 1) * 10 == 0) {
                map.centerAndZoom(pt, 6);
            }

            (function (li, arg, idx) {
                on(li, "click", function () {
                    $('#thematicQueryList a').removeClass('active');

                    var center = new esri.geometry.Point(arg.x * 1 + 120, arg.y * 1, map.spatialReference);
                    map.centerAndZoom(center, 6);
                });
            })(li, attr, i);
        }

        $("#exportCSV2").click(function () {
            exportAddressCSV(addressGraphicArr);
        })
    }


    //批量地址匹配文件解析结果
    $("#multiAddress_iframeContent").on("load", function () {
        var responseText = $("#multiAddress_iframeContent")[0].contentDocument.body.getElementsByTagName("pre")[0].innerHTML;

        $("#multiAddressModal").modal('hide');

        var index = responseText.lastIndexOf(".");
        var ext = responseText.substr(index + 1);
        var fileName = responseText.substr(0, index);
        const layerListType = "multiAddressLayerList";

        if (responseText.substr(responseText.length - 1, 1) == "}") {
            //excel的内容
            if (responseText == '{}') {
                failAlert("您加载的excel无内容，请检查后重新上传！");
            } else {
                resultJSON = eval('(' + responseText + ')');
                thematicGraphicLayer.clear();

                var fileNameWithExt = resultJSON.fileName + ".xls";

                localFileName = fileNameWithExt + "的批量地址检索结果";

                const titles = resultJSON.title;

                if (typeof (resultJSON.field) != "undefined") {
                    const texts = resultJSON.field[0][titles[0]];
                    doMultiMatch(texts, fileNameWithExt, layerListType);
                } else {
                    failAlert("您加载的excel无法解析，请检查后重新上传！");
                }
            }
        } else if (ext == "csv") {
            var filePath = "files/" + responseText;
            var fileNameWithExt = responseText;

            localFileName = fileNameWithExt + "的批量地址检索结果";

            $.ajax({
                url: filePath,
                datatype: "json",
                async: false,
                contentType: 'text/json,charset=utf-8',
                data: {},
                success: function (data) {
                    var dataStr = new String(data);
                    var lines = dataStr.split('\n');
                    var valuesArr = lines.slice(1, lines.length);
                    var texts = valuesArr.filter(item => {
                        return item && item.trim();
                    })
                    doMultiMatch(texts, fileNameWithExt, layerListType);
                }
            });
        }

        $("#mainio3").click();

    });


    function doMultiMatch(texts, fileNameWithExt, layerListType) {
        let addressResult = [];
        matchGraphics = [];
        matchGeometries = [];

        infoNotify(`后台正在对${texts.length}个地址进行批量匹配中，预计需要${Math.ceil(texts.length / 600)}分钟。匹配完成后会自动显示匹配结果，请稍后...`);

        console.log("开始匹配时间：", new Date())
        //防止浏览器限制websocket连接数量，每次发送300个请求
        let splitTexts = splitArr(texts, 300);

        let splitTextsLength = splitTexts.length;
        //递归splitTextsLength次

        let postPromise = num => {
            let texts = splitTexts[num];
            for (let i = 0; i < texts.length; i++) {
                let text = texts[i];
                text = text.replace(/#/g, '');
                addressResult.push(multiAddressMatch(text));
            }

            Promise.all(addressResult).then(() => {
                num++;

                if (num < splitTextsLength) {
                    postPromise(num);
                } else {
                    if (matchGeometries.length == 0) {
                        warningAlert("未匹配到相关地址！")
                    } else {
                        // setBufferParams(matchGeometries);
                        console.log("结束匹配时间：", new Date())

                        setBufferParams(matchGraphics);

                        createFeatureLayer(matchGraphics, fileNameWithExt, layerListType);
                    }
                }
                // $("#lcoalLayerList_" + (loaclDataGraphicsLayers.length + 1) + "_span").click();
            }, () => {

            });
        }

        //调用地址匹配的promise请求
        postPromise(0);
    }

    function multiAddressMatch(text) {
        const promise = new Promise((resolve) => {
            $.ajax({
                url: oneMapServerIP+"/OneMapServer/rest/services/address_p/as_CH.asmx/ASCH_AddressSearch?vSearch_word=" + text + "&vResult_count=200&token=" + GLOBAL_TOKEN,
                type: "get",
                dataType: "XML",
                success: function (response) {
                    map.infoWindow.hide();
                    if (typeof (response.getElementsByTagName("DZ_Result")[0]) != "undefined") {

                        if (typeof (response.getElementsByTagName("DZ_Result")[0].getElementsByTagName("DZ_Table")[0]) != "undefined") {

                            addressResult = response.getElementsByTagName("DZ_Result")[0].getElementsByTagName("DZ_Table")[0].children[1].children[0].children;
                            const address0 = addressResult[0].textContent;
                            const curText = text;
                            for (var i = 0; i < addressResult.length; i++) {
                                var item = addressResult[i];
                                var attr = {};
                                var infoCont = "";
                                //统一名称
                                var addname = "";
                                if (null != item.getElementsByTagName("POI")[0] && item.getElementsByTagName("POI")[0].textContent != null) {
                                    addname = item.getElementsByTagName("POI")[0].textContent;
                                } else if (null != item.getElementsByTagName("ROAD1")[0] && item.getElementsByTagName("ROAD1")[0].textContent != null) {
                                    addname = item.getElementsByTagName("ROAD1")[0].textContent;
                                } else if (null != item.getElementsByTagName("ADDRESS")[0] && item.getElementsByTagName("ADDRESS")[0].textContent != null) {
                                    addname = item.getElementsByTagName("ADDRESS")[0].textContent;
                                }

                                if (null != item.getElementsByTagName("POINT_X")[0] && item.getElementsByTagName("POINT_X")[0].textContent != null && null != item.getElementsByTagName("POINT_Y")[0] && item.getElementsByTagName("POINT_Y")[0].textContent != null) {
                                    var x = parseFloat(item.getElementsByTagName("POINT_X")[0].textContent);
                                    var y = parseFloat(item.getElementsByTagName("POINT_Y")[0].textContent);
                                } else {
                                    return
                                }

                                var area = "";
                                if (null != item.getElementsByTagName("REGION_QX")[0] && item.getElementsByTagName("REGION_QX")[0].textContent != null) {
                                    area = item.getElementsByTagName("REGION_QX")[0].textContent;
                                } else {
                                    area = "上海市";
                                }
                                var maccuracy = "";
                                if (null != item.getElementsByTagName("MACCURACY")[0] && item.getElementsByTagName("MACCURACY")[0].textContent != null) {
                                    maccuracy = item.getElementsByTagName("MACCURACY")[0].textContent;
                                } else {
                                    maccuracy = "0";
                                }
                                attr["原始地址"] = text;
                                attr["匹配到的地址"] = addname;
                                attr["所属区域"] = area;
                                attr["x"] = x;
                                attr["y"] = y;
                                attr["匹配度"] = maccuracy;
                                var sms = new PictureMarkerSymbol("img/marker/map-marker.png", 30, 30);
                                var pt = new Point(x, y, map.spatialReference);
                                infoCont += "<b>原始地址" + ":</b> " + text + " <br/>";
                                infoCont += "<b>匹配到的地址" + ":</b> " + addname + " <br/>";
                                infoCont += "<b>区县" + ":</b> " + area + " <br/>";
                                var infoTemplate = new InfoTemplate("<b>" + addname + "</b>", infoCont);
                                var graphic = new esri.Graphic(pt, sms, attr, infoTemplate);

                                matchGraphics.push(graphic);
                                matchGeometries.push(pt);
                            }

                        }

                    }
                    resolve();

                }
            });
        })

        return promise;
    }

});

//地址检索结果导出
function exportAddressCSV(addressGraphicArr) {
    let convertArrayOfObjectsToCSV = function (value) {
        var result, ctr, columnDelimiter, lineDelimiter, data;
        var keys = [];
        data = value.data || null;
        if (data == null || !data.length) {
            return null;
        }
        columnDelimiter = value.columnDelimiter || ',';
        lineDelimiter = value.lineDelimiter || '\n';
        keys = ["原始地址", "匹配到的地址", "所属区域", "x", "y", "匹配度"];
        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;

        keys = ["name", "district", "x", "y", "maccuracy"];

        data.forEach((item, index) => {
            let attributes = item.attributes;

            result += addressSearchText;

            keys.forEach(currentItem => {
                result += columnDelimiter;
                result += attributes[currentItem];
            })

            result += lineDelimiter;
        });

        return result;
    };


    var data = addressGraphicArr;
    var tableName = `${addressSearchText}的地址检索结果`;
    var csv = convertArrayOfObjectsToCSV({
        data: data
    });

    csv = "\ufeff" + csv;

    var blob = new Blob([csv], {
        type: "text/plain;charset=utf-8"
    });
    saveAs(blob, tableName + ".csv");
}